package vip.xiaonuo.biz.modular.detect.service.utils;

import java.io.*;

public class PythonProcessorAsync {
    private Process process;
    private BufferedReader reader;
    private final String scriptPath = "D:\\yolov5\\VOCData4\\finalfinalAutomation2.py";

    public void startPythonProcess() throws IOException {
        ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", "cd /d D:\\yolov5 && conda.bat activate yolov5 && cd VOCData4 && python", scriptPath);
        processBuilder.redirectErrorStream(true);  // 将标准输出和标准错误合并

        process = processBuilder.start();
        InputStream inputStream = process.getInputStream();
        reader = new BufferedReader(new InputStreamReader(inputStream));
    }

    public String processImage(String imagePath) throws IOException {
        if (process == null || !isProcessAlive(process)) {
            startPythonProcess();
        }

        // 向Python程序发送图片路径
        OutputStream outputStream = process.getOutputStream();
        outputStream.write((imagePath + "\n").getBytes());
        outputStream.flush();

        // 实时获取Python程序的输出
        StringBuilder resultBuilder = new StringBuilder();

        while (true) {
            if (reader.ready()) {
                String line = reader.readLine();
                if (line != null && !line.trim().isEmpty()) {
                    // 从Python进程的输出中读到了有效输出，添加到结果中
                    resultBuilder.append(line).append("\n");
                } else {
                    // 如果读到空行或者null，继续等待
                    continue;
                }
            }

            // 如果结果不为空，表示已经接收到有效输出，可以返回
            if (resultBuilder.length() > 0) {
                break;
            }
        }

        return resultBuilder.toString().trim();
    }


    public void closePythonProcess() {
        // 关闭管道和子进程
        try {
            reader.close();
            process.destroy();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean isProcessAlive(Process process) {
        try {
            process.exitValue();
            return false;  // 进程已经退出
        } catch (IllegalThreadStateException e) {
            return true;  // 进程仍在运行
        }
    }
}
